package com.jdchain.samples.rest.service;

import com.jd.blockchain.crypto.HashDigest;
import com.jd.blockchain.ledger.BlockchainKeypair;
import com.jd.blockchain.ledger.PreparedTransaction;
import com.jd.blockchain.ledger.TransactionResponse;
import com.jd.blockchain.ledger.TransactionTemplate;
import com.jd.blockchain.transaction.ContractReturnValue;
import com.jd.blockchain.transaction.GenericValueHolder;
import com.jdchain.samples.contract.SampleContract;
import com.jd.blockchain.sdk.BlockchainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

/**
 * 合约服务类
 */
@Service
public class ContractService {

    @Autowired
    private BlockchainService blockchainService;

    @Autowired
    private HashDigest ledgerHash;

    @Autowired
    private BlockchainKeypair adminKeypair;

    @Autowired
    @Qualifier("contractAddress")
    private String contractAddress;

    @Autowired
    @Qualifier("dataAccountAddress")
    private String dataAccountAddress;

    /**
     * 设置键值对
     */
    public String setKeyValue(String key, String value) {
        try {
            // 创建交易模板
            TransactionTemplate txTemplate = blockchainService.newTransaction(ledgerHash);
            
            // 获取合约代理
            SampleContract contract = txTemplate.contract(contractAddress, SampleContract.class);
            
            // 调用合约方法
            contract.set(dataAccountAddress, key, value);
            
            // 准备交易
            PreparedTransaction preparedTx = txTemplate.prepare();
            
            // 签名交易
            preparedTx.sign(adminKeypair);
            
            // 提交交易
            TransactionResponse response = preparedTx.commit();
            
            if (response.isSuccess()) {
                return response.getContentHash().toBase58();
            } else {
                throw new RuntimeException("交易执行失败: " + response.getExecutionState());
            }
        } catch (Exception e) {
            throw new RuntimeException("设置键值对失败: " + e.getMessage(), e);
        }
    }

    /**
     * 通过交易方式获取键值
     */
    public String getValueByTransaction(String key) {
        try {
            // 创建交易模板
            TransactionTemplate txTemplate = blockchainService.newTransaction(ledgerHash);
            // 获取合约代理
            SampleContract contract = txTemplate.contract(contractAddress, SampleContract.class);
            
            GenericValueHolder<String> userAddress = ContractReturnValue.decode(contract.get(dataAccountAddress, key));

            // 准备交易
            PreparedTransaction preparedTx = txTemplate.prepare();
            
            // 签名交易
            preparedTx.sign(adminKeypair);
            
            // 提交交易
            TransactionResponse response = preparedTx.commit();
            
            if (response.isSuccess()) {
                return userAddress.get();
            } else {
                throw new RuntimeException("交易执行失败: " + response.getExecutionState());
            }
        } catch (Exception e) {
            throw new RuntimeException("通过交易获取键值失败: " + e.getMessage(), e);
        }
    }
}

